$(function () {
    let shop = cookie.get('shop');

    if (shop) {
        $('.cart-cart').css('display', 'block');
        $('.cart-top').css('display', 'none');
        shop = JSON.parse(shop);

        let idList = shop.map(el => el.id).join();

        $.ajax({
            url: '../interface/cart.php',
            data: {
                idList
            },
            type: 'get',
            dataType: 'json'
        }).then(res => {
            let proTemp = '';
            let extraTemp = '';
            let gifTemp = '';
            let countTemp = '';
            let cou = 0;
            shop.forEach((el, i) => {
                proTemp = `
                <div class="product">
                    <div class="check">
                        <input type="checkbox" checked class="cek"><i class="iconfont icon-duigou"></i><span></span>
                    </div>
                    <div class="img"><img src="./${res[i].picture}" alt=""></div>
                    <div class="name">${el.name}</div>
                    <div class="price">${res[i].price}元</div>
                    <div class="num">
                        <a class="numSub">-</a><input type="text" readonly value="${el.num}"><a class="numAdd">+</a>
                    </div>
                    <div class="subtotal">${res[i].price*el.num}元</div>
                    <div class="action"><a class="exitall">X</a></div>
                </div> `;

                if (el.insurance.some(elm => elm !== "")) {
                    extraTemp = "";
                    el.insurance.filter(ele => ele !== "").map(function (el) {
                        extraTemp += `
                            <div class="extra" data-name=${el}>
                                <div class="img"><img src="./img/protect.png" alt=""></div>
                                <div class="name">
                                    <h5>${el}</h5>
                                    <p>1年一次意外损坏 官方原厂 免费维修</p>
                                </div>
                                <div class="price">59元</div>
                                <div class="num">1</div>
                                <div class="subtotal">59元</div>
                                <div class="action"><a class="exit">X</a></div>
                            </div>`;
                    })
                } else {
                    extraTemp = "";
                }


                if (res[i].gift) {
                    gifTemp = '';
                    let gif = JSON.parse(res[i].gift);
                    gifTemp += `
                    <div class="gifts">
                        <div class="gifts-item">
                            <div class="add">+</div>
                            <p>${gif[0].content}</p>
                        </div>
                    </div>`;
                } else {
                    gifTemp = '';
                }


                countTemp += `
                <div class="cart-cart-box" data-id="${el.id}">${proTemp}${extraTemp}${gifTemp}</div>
                `;
                $('.cart-cart-content').html(countTemp)


                cou += res[i].price * el.num;
                $('.cart-footer-price>span>em').text(cou)
            });

        }).catch(xhr => {
            console.log(xhr);
        });
    } else {
        $('.cart-cart').css('display', 'none');
        $('.cart-top').css('display', 'block');
    }

    if (cookie.get('account')) {
        $('.cart-login').css('display', 'none');
        $('.log-reg').html(`<a>${cookie.get('account')}</a>|<a class="exit">退出</a>`);
    } else {
        $('.cart-login').css('display', 'inline-block;');
    }

    $('.log-reg').on('click', '.exit', function () {
        cookie.remove('account');
        history.go(0);
    })
    if (shop) {
        $('.cart-footer-left>p>span').text(shop.length);
    } else {
        $('.cart-footer-left>p>span').text(0);
    }

    $('.cart-cart-content').on('click', '.exit', function () {
        $(this).parent().parent().parent().attr('data-id');
        let ind = shop.findIndex(el => el.id == $(this).parent().parent().parent().attr('data-id'));
        let insInd = shop[ind].insurance.findIndex(el => el == $(this).parent().parent().attr('data-name'))
        shop[ind].insurance.splice(insInd, 1, '');
        cookie.set('shop', JSON.stringify(shop))
        history.go(0);
        $(this).parent().parent().remove();

    })

    $('.cart-cart-content').on('click', '.exitall', function () {
        $(this).parent().parent().parent().remove();
        let ind = shop.findIndex(el => el.id == $(this).parent().parent().parent().attr('data-id'));
        shop.splice(ind, 1);
        cookie.set('shop', JSON.stringify(shop))
        if (cookie.get('shop') == '[]') {
            cookie.remove('shop')
        }
        history.go(0);
    })

    $('.cart-cart-content').on('click', '.num>.numSub', function () {
        if ($(this).next().val() == 1) {
            alert('修改数量不能小于0');
        } else {
            $(this).next().val($(this).next().val() - 1);
            let ind = shop.findIndex(el => el.id == $(this).parent().parent().parent().attr('data-id'));
            shop[ind].num--;
            cookie.set('shop', JSON.stringify(shop));
            $(this).parent().next().text(parseInt($(this).parent().next().text()) - parseInt($(this).parent().prev().text()) + "元")
            $('.cart-footer-price>span>em').text(parseInt($('.cart-footer-price>span>em').text()) - parseInt($(this).parent().prev().text()))
        }
    })

    $('.cart-cart-content').on('click', '.num>.numAdd', function () {
        $(this).prev().val(parseInt($(this).prev().val()) + 1);
        let ind = shop.findIndex(el => el.id == $(this).parent().parent().parent().attr('data-id'));
        shop[ind].num++;
        cookie.set('shop', JSON.stringify(shop));
        $(this).parent().next().text(parseInt($(this).parent().next().text()) + parseInt($(this).parent().prev().text()) + "元")
        $('.cart-footer-price>span>em').text(parseInt($('.cart-footer-price>span>em').text()) + parseInt($(this).parent().prev().text()))

    })

    let couPrice;
    $('.cekAll').on('click', function () {
        if ($('.cekAll')[0].checked) {
            Array.from($('.cek')).forEach(el => el.checked = true);
            $('.cart-footer-left>p>span').text(shop.length);
            $('.cart-footer-price>span>em').text(couPrice);
        } else {
            Array.from($('.cek')).forEach(el => el.checked = false);
            couPrice = $('.cart-footer-price>span>em').text();
            $('.cart-footer-left>p>span').text('0');
            $('.cart-footer-price>span>em').text('0');
        }
    })

    $('.cart-cart-content').on('click', '.cek', function () {
        if (Array.from($('.cek')).some(el => el.checked == false)) {
            $('.cekAll')[0].checked = false;
        } else if (Array.from($('.cek')).every(el => el.checked == true)) {
            $('.cekAll')[0].checked = true;
        }
        if ($(this)[0].checked) {
            $('.cart-footer-price>span>em').text(parseInt($('.cart-footer-price>span>em').text()) + parseInt($(this).parent().next().next().next().next().next().text()));
            $('.cart-footer-left>p>span').text(parseInt($('.cart-footer-left>p>span').text()) + 1);

        } else {
            $('.cart-footer-price>span>em').text(parseInt($('.cart-footer-price>span>em').text()) - parseInt($(this).parent().next().next().next().next().next().text()));
            $('.cart-footer-left>p>span').text(parseInt($('.cart-footer-left>p>span').text()) - 1);
        }
    })

    $.ajax({
        type: "get",
        url: "../interface/index.php",
        dataType: "json"
    }).then(res => {

        let template = '';

        res.forEach(elm => {
            template += `
                    <div class="item" data-id="${elm.id}">
                        <img src="./${elm.picture}">
                        <h3>${elm.title}</h3>
                        <span>${elm.price}元</span>
                        <p>64.1万人好评</p>
                        <div class="addcart">加入购物车</div>
                    </div>
        `;
        });

        $('.recommend-list').html(template);

        $('.recommend-list').on('click', '.addcart', function () {
            add($(this).parent().attr('data-id'), 1, $(this).prev().prev().prev().text());
            history.go(0);
        })


    }).catch(xhr => {
        console.log(xhr.status);
    });

    //购物车
    function add(id, num, name, ...insurance) {
        let product = {
            id,
            num,
            name,
            insurance
        };

        let shop = cookie.get('shop'); // 从cookie中获取数据

        if (shop) { // 判断cookie中是否有数据
            // 有数据则获得一个JSON字符串
            // 转成对象
            shop = JSON.parse(shop);

            // 判断当前商品的id在cookie数据中是否已经存在 如果已经存在则修改数量 不添加数据
            if (shop.some(el => el.id == id)) {
                let index = shop.findIndex(elm => elm.id == id); // 找到当前商品的索引
                let count = parseInt(shop[index].num); // 获得当前商品的数量
                count++;
                shop[index].num = count;
                shop.filter(el => el.id == id).map(el => el.insurance = insurance)
            } else { // 当前商品id在cookie数据中不存在 添加数据
                shop.push(product);
            }



        } else { // 没有获得cookie数据时 初始化成一个数组 然后添加数据
            shop = [];
            shop.push(product);
        }

        cookie.set('shop', JSON.stringify(shop));
    }

    $('.cart-footer-clear').on('click', function () {
        if (!cookie.get('account')) {
            alert('请先登录');
            setTimeout(() => {
                self.location = './login.html';
            }, 200);
        } else {
            alert('信不信给你弹出个二维码');
        }
    })
})